var isAndroid2 = navigator.userAgent.match(/Android(\s*)2(\.\d)+/i);

$(function() {
	$("#lodingImage").ajaxStart(function() {
		$(this).show();
	}).ajaxStop(function(){
		$(this).hide();
	});
});

$(function(){
	if(location.hash.length < 1){
		$("body").bind("onload",function(){
			setTimeout("scrollTo(0,1)", 100);
		});
	}

	$(window).bind("load",function(){
		setTimeout(function(){
			$("img._delayImage").each(function(){
				$(this).attr("src",$(this).attr("data-src"));
			});
    	},0);
	});

	if($("#loginModalCROOZ").length){
		$("#loginModalCROOZ").click(function(){
			$(this).removeClass("db").addClass("dn");
			$("#loginModalCROOZ_display").removeClass("dn");
		});
	}

	$("._tabArea")._tab();
	$(".body")._onSubmit();
	// $(".search_form_wrap ._setToggleSwich").targetToggle("_open");
	$("._toTop")._toTop();
	$("._toggleMenuBtn").targetToggle();
});

function make_submit_field( name, value, formid ){
	var submit_area_id = 'submit_area';
	if( formid != undefined ){
		submit_area_id = 'submit_area_' + formid;
	}
	document.getElementById(submit_area_id).innerHTML = '<input type="hidden" name="' + name + '" value="' + value + '">';
	if( formid != undefined ){
		document.getElementById(formid).submit();
	}
	else {
		document.forms[0].submit();
	}
}

$(function(){
	//submit
	$("body").on("click", "._submit", function(e){
		e.preventDefault();
		$("+input[type='submit']",this).click();
	});
});

jQuery.fn.getAbsolutePosition = function() {
	var node = $(this).get(0),
		left = 0,
		top = 0;
	while(node != document.body) {
		left += node.offsetLeft;
		top += node.offsetTop;
		node = node.offsetParent;
	}
	return {
		left: left,
		top: top
	};
};

(function($) {
	//モーダル用プラグイン add 2015/12/18
	$.fn._modalCtrl = function(options) {
		var
			 $ele = this
			,opts = $.extend({}, {
				 bgSpeed : 200 //オーバーレイの表示速度
				,contentSpeed : 300 //モーダルの表示速度
				,posTop : 100 //モーダルの表示位置
			}, options)
		;
		//モダールを開く
		var _openModal = function($target) {
			if(!($('._modal_over_lay').length))$(document.body).prepend('<div class="_modal_over_lay" onclick=""></div>');
			$('._modal_over_lay')
					.fadeIn(opts.bgSpeed)
					.addClass('_modal_close')
					.css({
						 'position': 'fixed'
						,'-webkit-tap-highlight-color': 'rgba(0,0,0,0)'
					});

			if (navigator.userAgent.indexOf('Android 2') != -1) {
				$('#contents').css({
					'-webkit-tap-highlight-color': 'rgba(0,0,0,0)'
				});
			}

			//モーダルのポジション位置調整
			if (typeof $target.data('modal-top') !== 'undefined') opts.posTop = Number($target.data('modal-top'));

			$target
				.fadeIn(opts.contentSpeed)
				.css('top', $(window).scrollTop() + opts.posTop);
				// .find('._modal_close').removeClass('dn');

			return false;
		};

		//モーダルを閉じる
		var _closeModal = function() {
			$('._modal_over_lay').fadeOut(opts.bgSpeed).remove();
			$('.open_content').fadeOut(opts.contentSpeed);

			if (navigator.userAgent.indexOf('Android 2') != -1) {
				$('#contents').css({
					'-webkit-tap-highlight-color': ''
				});
			}

			return false;
		};

		//閉じるボタン用
		$(document).on('click', '._modal_close', function(e) {
			e.preventDefault();
			_closeModal();
			return false;
		});

		//modalイベント定義
		$ele.each(function() {
			var $content = $('#' + $(this).data('modal-content'));
			if ($content.length > 0) {
				$content.css({
					 'display': 'none'
					,'position': 'absolute'
					,'width': '90%'
					,'left': '50%'
					,'margin-left': '-45%'
					,'z-index': 10100
				})
				.addClass('open_content');

				$(document).on('click', '[data-modal-content=' + $(this).data('modal-content') + ']', function(e) {
					e.preventDefault();
					_openModal($content);
					return false;
				});
			}
		});

		//modal defaut実行
		$ele.each(function() {
			var $content = $('#' + $(this).data('modal-content'));
			if ($('#' + $(this).data('modal-content')).data('modal-default')) {
				setTimeout(function() {
					_openModal($content);
				}, 300);
			}
		});

		return this;
	};

	//leanModal v1.1 by Ray Stone - http://finelysliced.com.au
	//Dual licensed under the MIT and GPL
	$.fn.extend({
		leanModal : function(options) {
			var defaults = {
			/* closeButton: null */
			};
			var overlay = $("<div id='lean_overlay'></div>");
			$("body").append(overlay);
			options = $.extend(defaults, options);

			function close_modal(modal_id) {
				$("#lean_overlay").fadeOut(200);
				$(modal_id).css({
					"display" : "none"
				})
			}

			return this.each(function() {
				var o = options;
				$(this).click(function(e) {
					var modal_id = $(this).attr("href");


					$("#lean_overlay").click(function(e) {
						e.preventDefault();
						close_modal(modal_id)
					});
					$(o.closeButton).click(function(e) {
						e.preventDefault();
						close_modal(modal_id)
					})

					var scrT = window.pageYOffset,
						windowWidth = (!(window.innerWidth)) ? document.documentElement.clientWidth : window.innerWidth,
						windowHeight = (!(window.innerHeight)) ? document.documentElement.clientHeight : window.innerHeight,
						cw = (windowWidth - $(modal_id).width())/2,
						ch = ((windowHeight - $(modal_id).height())/2) + scrT;
					if(cw < 0){
						cw = 10;
					}
					if(ch < 0){
						ch = 10 + scrT;
					}else if(windowHeight < $(modal_id).height()){
						ch = 10 + scrT;
					}

					$("#lean_overlay").css({
						"display" : "block",
						opacity : 0
					});
					$("#lean_overlay").fadeTo(200, o.overlay);
					$(modal_id).css({
						"display" : "block",
						"position" : "absolute",
						"opacity" : 0,
						"z-index" : 11000,
						"left" : 50 + "%",
						"margin-left" : -150 + "px",
			            "top": ch
			            /*"left": cw*/
					});
					$(modal_id).fadeTo(200, 1);
					e.preventDefault()
				})
			});
		}
	})

	if (!window.requestAnimationFrame) {
		window.requestAnimationFrame = window.webkitRequestAnimationFrame ||
								   window.mozRequestAnimationFrame ||
								   window.oRequestAnimationFrame ||
								   window.msRequestAnimationFrame ||
								   (function(){
								   		return function(main){
								   			return setTimeout(main, 1000);
								   		};
								   	}());
		}
		if (!window.cancelAnimationFrame) {
		window.cancelAnimationFrame = window.webkitCancelAnimationFrame ||
									window.mozCancelAnimationFrame ||
									window.oCancelAnimationFrame ||
									window.msCancelAnimationFrame || clearTimeout;
		}
		$.fn.countdown = function(endFunc) {
		return $(this).each(function() {
			var root = $(this),
				tl = root.data('limittime') * 1000,
				day2Obj = root.find('.day2').children(),
				day1Obj = root.find('.day1').children(),
				hour3Obj = root.find('.hour3').children(),
				hour2Obj = root.find('.hour2').children(),
				hour1Obj = root.find('.hour1').children(),
				minute2Obj = root.find('.minute2').children(),
				minute1Obj = root.find('.minute1').children(),
				second2Obj = root.find('.second2').children(),
				second1Obj = root.find('.second1').children(),
				timer = null;
			var dayAddHourFlug = root.hasClass("_dayAddHour"),
					threeDegitFlg = root.hasClass("_3degitHour");
			function animate(){
				var today		= new Date().getTime(),
					diffTime	= tl - today;
				if ( diffTime > 0 ) {
					if(dayAddHourFlug){
						var hour	= Math.floor(diffTime / 3600000),
							day,
							day2 = 0,
							day1 = 0;
					}else{
						var day		= Math.floor(diffTime / 86400000),
							day2 = ((day > 9)? Math.floor(day/10) : 0),
							day1 = (day % 10),
							hour	= Math.floor(diffTime / 3600000) % 24;
					}
					if(threeDegitFlg){
						var min		= Math.floor(diffTime / 60000) % 60,
							sec		= Math.floor(diffTime / 1000) % 60 % 60,
							hour3 = ((hour > 99)? Math.floor(hour/100) : 0),
							hour2 = ((hour > 9)? Math.floor(hour/10) % 10 : 0),
							hour1 = (hour % 10),
							minute2 = ((min > 9)? Math.floor(min/10) : 0),
							minute1 = (min % 10),
							second2 = ((sec > 9)? Math.floor(sec/10) : 0),
							second1 = (sec % 10);
					}else{
						var min		= Math.floor(diffTime / 60000) % 60,
							sec		= Math.floor(diffTime / 1000) % 60 % 60,
							hour2 = ((hour > 9)? Math.floor(hour/10) : 0),
							hour1 = (hour % 10),
							minute2 = ((min > 9)? Math.floor(min/10) : 0),
							minute1 = (min % 10),
							second2 = ((sec > 9)? Math.floor(sec/10) : 0),
							second1 = (sec % 10);
					}
					day2Obj.removeClass().addClass("n" + day2 );
					day1Obj.removeClass().addClass("n" + day1 );
					hour3Obj.removeClass().addClass("n" + hour3 );
					hour2Obj.removeClass().addClass("n" + hour2 );
					hour1Obj.removeClass().addClass("n" + hour1 );
					minute2Obj.removeClass().addClass("n" + minute2 );
					minute1Obj.removeClass().addClass("n" + minute1 );
					second2Obj.removeClass().addClass("n" + second2 );
					second1Obj.removeClass().addClass("n" + second1 );
					delete today;
					delete diffTime;
					delete day;
					delete hour;
					delete min;
					delete sec;
					delete day2;
					delete day1;
					delete hour3;
					delete hour2;
					delete hour1;
					delete minute2;
					delete minute1;
					delete second2;
					delete second1;
					timer = requestAnimationFrame(animate);
				}else{
					cancelAnimationFrame(timer);
					if($.isFunction(endFunc)){
						endFunc(root);
					}
					delayModalFn();
				}
			}
			animate();

			function delayModalFn(){
				if ($("._delayTrigger").size() <= 0) return;
				var delayTarget = $("._delayTrigger"),
					dalayModal  = delayTarget.find("._modalContents"),
					dalayMdClose= delayTarget.find("._modalClose"),
					scrtop      = $(window).scrollTop() +50;
					delayTarget.css("display","block");
					dalayModal.css("top",scrtop);
					dalayMdClose.on('click', function(e){
						e.preventDefault();
						location.reload();
					});
			};
		});
	};

	$.fn._tab = function(){
		var	setClass = {
				"select" : "_selected",
				"tab" : "_tab",
				"contents" : "_contents"
			};
		$(this).each(function(){
			var nodeIndex = {
				"self" : $(this),
				"tab" : $(this).find("."+setClass.tab),
				"contents" : $(this).find("."+setClass.contents)
			};
			nodeIndex.tab.on("click",function(e){
				e.preventDefault();
				var num = nodeIndex.tab.index($(this));
				nodeIndex.self.find("."+setClass.select).removeClass(setClass.select);
				nodeIndex.tab.eq(num).closest("li").addClass(setClass.select);
				nodeIndex.contents.removeClass(setClass.select).eq(num).addClass(setClass.select);
			});
		});
		return this;
	};

	$.fn._onSubmit = function(){
		$('._changeSelectSubmit').on('change', function(){
		    $(this).closest('form').submit();
		});
		$('._checkCheckBoxSubmit').on('click', function(){
		    $(this).closest('form').submit();
		});
		$('._radioClickSubmit').on('change', function(){
		    $(this).closest('form').submit();
		});
	};

	$.fn._toTop = function(){
		$(this).each(function(){
			var nodeIndex = {
				"self" : $(this)
			};
			nodeIndex.self.bind("click", function(e){
				e.preventDefault();
				$('html, body').animate({ scrollTop: 0 });
			});
		});
		return this;
	};

	$.fn._categoryToggle = function(){
		var shopToggleTrigger = $('._categoryToggleTrigger'),
			categoryToggle = $('._categoryToggle');
		shopToggleTrigger.each(function(){
			var self				= $(this),
				shopToggleContents	= self.parent('._categoryToggleContents'),
				shopToggleTarget	= self.next('._categoryToggleTarget');
			self.on('click', function(e){
				e.preventDefault();
				if(shopToggleContents.hasClass('_on')){
					self.next(shopToggleTarget).slideUp();
					shopToggleContents.removeClass('_on');
				}else{
					self.next(shopToggleTarget).slideDown();
					shopToggleContents.addClass('_on');
				}
			});
		});
		categoryToggle.each(function(){
			var self = $(this);
			self.next("._categoryToggleMore").on("click",function(e){
				var btn = $(this);
				e.preventDefault();
				self.find("._categoryToggleMoreContents").slideDown("",function(){
					btn.hide();
				});
			});
		});
	}

	$.fn._fitZoom = function(){
		var self = $(this);
		var baseWidth = $(this).width();
		exec = function(){
			var toWidth = $(window).width();
			self.css("zoom",toWidth/baseWidth);
		}
		exec();
		$(window).on("orientationchange resize",exec);
	}

})(jQuery);

$(function() {
	$("._fitZoom")._fitZoom();
});

$(function() {
	$("a[rel*=leanModal]").leanModal({
		top : 10,
		overlay : 0.9,
		closeButton : ".modal_stock_close"
	});
});

/* キーワード同時変更 */
function pasteText(formObj){
	var	copyText = formObj.find("._copyText");
	copyText.each(function(){
		var	copyObj = $(this)
		copyObj.on("change",function(e){
			targetText = copyObj.val();
			copyText.attr('value',targetText);
		});
	});
	var	copySelect = formObj.find("._copySelect");
	copySelect.each(function(){
		var	copySelectObj = $(this)
		copySelectObj.on("change",function(e){
			targetSelect = copySelectObj.val();
			copySelect.attr('value',targetSelect);
		});
	});
}
$("form._enablePasteText").each(function(){
	pasteText($(this));
});

function pasteForm(formObj){
	var	eachCopyText = formObj.find("._eachCopyText")
	eachCopyText.each(function(){
		var eachCopyTextObj	= $(this);
		eachCopyTextObj.on("change",function(){
			var	eachTargetText = $(this).val(),
				eachCopyTextObjId = $(this).attr("data-copyId");
			eachCopyText.each(function(){
				if($(this).hasClass(eachCopyTextObjId)){
					$(this).attr("value",eachTargetText);
				}
			})
		});
	});
	var	eachCopySelect = formObj.find("._eachCopySelect")
	eachCopySelect.each(function(){
		var eachCopySelectObj	= $(this);
		eachCopySelectObj.on("change",function(){
			var	eachTargetSelect = $(this).val(),
				eachCopySelectObjId = $(this).attr("data-copyId");
			eachCopySelect.each(function(){
				if($(this).hasClass(eachCopySelectObjId)){
					$(this).attr("value",eachTargetSelect);
				}
			})
		});
	});
	var	copyRadio = formObj.find("._copyRadio")
	copyRadio.each(function(){
		var copyRadioObj	= $(this);
		copyRadioObj.on("click",function(){
			var	copyRadioObjId = $(this).attr("data-copyId");
			copyRadio.each(function(){
				if($(this).hasClass(copyRadioObjId)){
					$(this).attr("checked", true );
				}
			})
		});
	});
	var	copyCheckbox = formObj.find("._copyCheckbox")
	copyCheckbox.each(function(){
		var copyCheckboxObj	= $(this);
		copyCheckboxObj.on("click",function(){
			var copyCheckboxObjId = $(this).attr("data-copyId");
			copyCheckbox.each(function(){
				if($(this).hasClass(copyCheckboxObjId)){
					if(copyCheckboxObj.prop("checked")){
						$(this).attr("checked", true );
					}else{
						$(this).attr("checked", false );
					}
				}
			})
		});
	});
};
/* カテゴリ選択時にサブカテゴリ表示 */
function subGenreForm(formObj){
	var	genreSelect = formObj.find("._genreSelect");
	genreSelect.each(function(){
		var genreSelectObj	= $(this);
		genreSelectObj.on("change",function(){
			var	genreId		 = $(this).val(),
				subGenreWrap = $(".searchSubGenreWrap"),
				subGenreSelect = subGenreWrap.find("select");
			if(genreId.length){
				subGenreSelect.each(function(){
					subGenreOption = $(this).find("option");
					if($(this).attr("data-parentGenreId") == genreId){
						$(this).removeClass("dn").addClass("db");
						$(this).removeAttr("disabled");
						subGenreOption.removeAttr("disabled");
						subGenreOption.each(function(){
							if(!$(this).val().length){
								$(this).attr("selected","selected");
							};
						});
					}else{
						$(this).removeClass("db").addClass("dn");
						$(this).attr("disabled","disabled");
						subGenreOption.attr("disabled","disabled");
						subGenreOption.attr("selected",false);
					}
				});
				subGenreWrap.slideDown();
			}else{
				subGenreWrap.slideUp();
				subGenreSelect.each(function(){
					subGenreOption = $(this).find("option");
					subGenreOption.attr("disabled","disabled");
					subGenreOption.attr("selected",false);
				});
			}
		});
	});
};
function effectiveAggregateForm(formObj){
	var	effAggSelect = formObj.find("._effAggSelect");
	effAggSelect.each(function(){
		var effAggSelectObj	= $(this),
			effAggValue		= effAggSelectObj.attr("data-effAggValue");
		effAggSelectObj.each(function(){
			$(this).on("change",function(){
				$("._effAggSelectTarget").each(function(){
					if($(this).val() == effAggValue){
						$(this).attr("checked", true );
					}
				});
			});
		});
	});
};
$("body").each(function(){
	subGenreForm($(this));
	pasteForm($(this));
	effectiveAggregateForm($(this));
});

/* 一覧系一括チェック */
$(function() {
	var allchekbtn = $("._allCheck a")
	allchekbtn.on("click",function(e){
		e.preventDefault();
		if(allchekbtn.hasClass("unchecked")){
			$(".check_common_btn input").attr('checked',true)
			allchekbtn.removeClass("unchecked").addClass("checked")
		}else{
			$(".check_common_btn input").attr('checked',false)
			allchekbtn.removeClass("checked").addClass("unchecked")
		}
	});
});

/* select選択時にリンク */
$(function() {
	$('._selectedLink').on('change', function() {
		var linkUrl = $('._selectedLink').val();
		location.href = linkUrl;
	});
});

/* radioボタン選択時にリンク */
$(function() {
	$("label._clickSubmit").on("click",function(){
		var formObj = $("#listProductItemLink"),
			actionUrl = $(this).attr("data-product-url");
		formObj.attr('action',actionUrl);
		setTimeout(function(){
			formObj.submit();
		},0);
	});
});

$.oneLineTxt = function(txt){
	if($("#oneLineTxt:not(:animated)").length){
		$("#oneLineTxt:not(:animated)").find(".text").html(txt);
		$("#oneLineTxt:not(:animated)").width($(window).width()).show();
		setTimeout(function(){
			$("#oneLineTxt").fadeOut();
		},2000);
	}
};
$(function() {
	(function(txt){
		if(txt.length <= 0) return;
		var t = txt.data("onelinetxt");
		$.oneLineTxt(t);
	})($('#stateOneLineTxt'));
});

$("body").ajaxError(function(event, jqXHR, ajaxSettings, thrownError){
	if(thrownError == "timeout"){
		$.oneLineTxt("接続がタイムアウトしました。<br />電波の良い場所で再度お試しください");
	}
});

/* summerfestival用カウントダウン */
$(function(){
	var countDownEndFunc = function(d){
		d.find('.number').children().removeClass().addClass("no");
	};
	$("#lpCountDown, #headerCountDown").countdown(countDownEndFunc);
});

/*カテゴリ*/
$(function(){
    $('_categoryToggle')._categoryToggle();
});

/* #72413 [SHOPLIST]アプリインストール促進 webページ対応 */
$(function(){
	var app_banner_cookie_name	= 'app_banner_install',
		$app_banner 			= $( '#app_banner' ),
		$app_banner_close 		= $( '#app_banner_close' ),
		//$app_banner_install		= $( 'div.box_desc dd button' ),
		$app_banner_install		= $( '#app_install' ),
		//モバイルOSの種類を取得
		getMobileOS 			= function ( ){
			var userAgent = navigator.userAgent || navigator.vendor || window.opera;
			if( userAgent.match( /iPad/i ) || userAgent.match( /iPhone/i ) || userAgent.match( /iPod/i ) )
				return 'iOS';
			else if( userAgent.match( /Android/i ) )
				return 'Android';
			else
				return 'unknown';
		},
		//モバイルOSにより飛ぶリンクを取得
		getAppInstallURL		= function( os ){
			var url = 'https://t.metaps.biz/v1/cpi/click?',
				params = {
					append_app_conv_trk_params	: 1,
					network_id					: 1599,
					device_id					: 'device_id',
					site_id						: 1,
					campaign_id					: (os === 'iOS') ?	'kojp-co-crooz-ios-appshoplist-23-ios54fe8c6ca0b258e67b14d172f8' :
																	'kojp-co-crooz-android-shoplist-6a-android54fe8c67b717bd422d02bb49ab'
				};
			return url + $.param( params );
		},
		//１週間のクッキーの作成、１週間以内にアプリインストールバナーを表示させない
		createCookie				= function( ){
			var app_banner_today 	= new Date( );
			var app_banner_expire 	= new Date( app_banner_today.getTime( ) + ( 7 * 24 * 60 * 60 * 1000 ) );
			var app_banner_cookie 	= app_banner_cookie_name + '=1; expires=' + app_banner_expire.toUTCString( ) + '; path=/';
			document.cookie 		= app_banner_cookie;
		};

	if ( ( document.cookie && document.cookie.indexOf( app_banner_cookie_name + '=1' ) != -1 ) ||
			!$app_banner.length || getMobileOS( ) === 'unknown' ) return;

	//アプリインストールバナー表示させる
	$app_banner.show( );

	//アプリインストールバナー非表示
	$app_banner_close.on( 'click', function( e ){
		createCookie( );
		$app_banner.hide( 'fast' );
	} );

	//アプリインストールバナー非表示し、１週間のクッキーの作成し、非表示させる
	$app_banner_install.on( 'click', function( e ){
		createCookie( );
		window.location.replace( getAppInstallURL( getMobileOS( ) ) );
		$app_banner.hide( 'fast' );
	} );
});

/* 共通モーダル */
$(function() {
	$('[data-modal-content]')._modalCtrl();
});

/* #96616 初回購入ポイント20倍対応 */
$(function(){
	if($("._onceTimeFresher").length){
		var visitorName = "freshersVisitorFlg",
			expireCookieFn = function(cookiename){
			var nowTimeDate = new Date(),
				nowYear     = nowTimeDate.getFullYear(),
				nowMonth    = nowTimeDate.getMonth()+1,
				nowDate     = nowTimeDate.getDate(),
				hms         = " 23:59:59";
			if (nowMonth < 10){nowMonth = "0"+nowMonth;}
			if (nowDate < 10){nowDate = "0"+nowDate;}
			var jstTime     = nowYear+"-"+nowMonth+"-"+nowDate+hms,
				expireDate  = new Date(jstTime).toUTCString(),
				ON_FLG      = 1,
				cookieData  = {
					"name"    : cookiename + "=" + ON_FLG,
					"path"    : ";path=" + "/",
					"expires" : ";expires=" + expireDate,
					"domain"  : ";domain=" + ""
				};
			document.cookie = cookieData.name + cookieData.path + cookieData.expires + cookieData.domain;
		};

		// 訪問者ベースでCookieセット
		if(!document.cookie.match(visitorName)){
			expireCookieFn(visitorName);
		}
		// bnrクリックでCookieセット
		$(document).on("click","._onceTimeFresher a",function(e){
			e.preventDefault();
			expireCookieFn("freshersPointUpFlg");
		});
	}
});